package QQCharting;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Receiver implements Runnable {

    DatagramSocket server = null;
    DatagramPacket packet = null;

    public Receiver(DatagramSocket server) {
        this.server = server;
    }

    @Override
    public void run() {
        try{
            byte[] buf = new byte[1024];
            packet = new DatagramPacket(buf,buf.length);
            while(true){
                // 得到接收的信息
                server.receive(packet);
                // 将得到的信息转化为字符串
                String str = new String(packet.getData(),0,packet.getLength());
                // 输出信息
                System.out.println(packet.getAddress()+":"+packet.getPort()+"发来了信息："+str);
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (server!=null){
                server.close();
            }
        }
    }
}
